package com.jhjx.wx.mp.handler;

import com.jhjx.wx.mp.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

@Component
public class MsgHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService, WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服") && weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
                //获取当前系统时间的“时”
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                if (hour>=9 && hour<=18) {
                    return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
                } else {
                    String content = "您好，在线客服服务时间为工作日9:00-18:00。";
                    return new TextBuilder().build(content, wxMessage, weixinService);
                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        //TODO 组装回复消息
        String content = "您好，如有商品相关问题请咨询在线客服，发送“客服”即可。";
        return new TextBuilder().build(content, wxMessage, weixinService);
    }

}
